<?php

namespace Manager;

use W3\Util;
use Base\Users as Manager;

!defined('W3_ROOT_DIR') AND exit;

/**
 * Users编辑管理基类
 *
 * @author edikud
 * @date 2022/10/22
 * @copyright Copyright (c) 2022 W3 (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Users extends Manager
{
    /**
     * 增加用户
     *
     * @access public
     * @param array $values 用户结构数组
     * @return integer
     */
    public function addUsers(array $values)
    {
        /** 构建插入结构 */
        $user = [
            'group'         =>  empty($values['group']) ? 'visitor' : $values['group'],
			'name'          =>  empty($values['name']) ? '' : htmlspecialchars($values['name']),
			'nickName'      =>  empty($values['nickName']) ? '' : htmlspecialchars($values['nickName']),
            'password'      =>  empty($values['password']) ? '' : $values['password'],
            'salt'          =>  empty($values['salt']) ? sha1(Util::randstring(20)) : $values['salt'],
            'mail'          =>  empty($values['mail']) ? '' : $values['mail'],
            'mobile'        =>  empty($values['mobile']) ? '' : $values['mobile'],
            'url'           =>  empty($values['url']) ? '' : $values['url'],
            'sign'          =>  empty($values['sign']) ? '' : $values['sign'],
            'intro'         =>  empty($values['intro']) ? '' : $values['intro'],
            'scores'        =>  empty($values['scores']) ? 0 : intval($values['scores']),
            'ip'            =>  empty($values['ip']) ? $this->request->ip(true) : $values['ip'],
            'created'       =>  empty($values['created']) ? $this->config->time : $values['created'],
            'logged'        =>  empty($values['logged']) ? 0 : intval($values['logged']),
            'activated'     =>  empty($values['activated']) ? 0 : intval($values['activated']),
        ];

        if (!empty($values['uid'])) {
            $user['uid'] = $values['uid'];
        }
		
		/** 保证密码不为空 */
        if (empty($values['password'])) {
            $user['password'] = substr(uniqid(), 7);
        }
		
		$user['password'] = Util::passwordHash($user['password']);

        return $this->db
		    ->insert('table.users')
		    ->rows($user)
			->lastId();
    }

    /**
     * 更新用户
     *
     * @access public
     * @param int $uid 用户uid
     * @param array $values 用户结构数组
     * @return integer
     */
    public function updateUsers($uid, array $values)
    {
        /** 构建插入结构 */
        $update = [
            'group'         =>  empty($values['group']) ? 'visitor' : $values['group'],
			'name'          =>  empty($values['name']) ? '' : htmlspecialchars($values['name']),
			'nickName'      =>  empty($values['nickName']) ? '' : htmlspecialchars($values['nickName']),
            'salt'          =>  empty($values['salt']) ? sha1(Util::randstring(20)) : $values['salt'],
            'mail'          =>  empty($values['mail']) ? '' : $values['mail'],
            'mobile'        =>  empty($values['mobile']) ? '' : $values['mobile'],
            'url'           =>  empty($values['url']) ? '' : $values['url'],
            'sign'          =>  empty($values['sign']) ? '' : $values['sign'],
            'intro'         =>  empty($values['intro']) ? '' : $values['intro'],
            'scores'        =>  empty($values['scores']) ? 0 : intval($values['scores']),
            'ip'            =>  empty($values['ip']) ? $this->request->ip(true) : $values['ip'],
            'logged'        =>  empty($values['logged']) ? 0 : intval($values['logged']),
            'activated'     =>  empty($values['activated']) ? 0 : intval($values['activated']),
        ];
		
        $user = [];
        foreach ($values as $key => $val) 
		{
            if (array_key_exists($key, $update)) {
                $user[$key] = $update[$key];
            }
        }
		
        /** 更新创建时间 */
        if (!empty($values['created'])) {
            $user['created'] = $values['created'];
        }
		
		/** 保证密码不为空 */
        if (!empty($values['password'])) {
		    $user['password'] = Util::passwordHash($values['password']);
        } else {
			unset($user['password']);
		}
		
        return $this->db
		    ->update('table.users')
		    ->where('uid = ?', $uid)
			->rows($user)
			->affected();
    }

    /**
     * 删除用户
     *
     * @access public
     * @return void
     */
    public function deleteUsers($uid)
    {
        return $this->db
		    ->delete('table.users')
		    ->where('table.users.uid = ?', $uid)
			->affected();
    }
	
	/**
	 * 递增数值
	 *
	 * @access public
	 * @param int|string $uid 
	 * @param string     $field  
	 * @param int        $num 
	 * @return false|int 
	 */
	public function incr( $uid, $field, $num = 1 )
	{
		$num = max(1, (int) $num);
		
        /** 更新内容数 */
		return $this->db->update('table.users')
		    ->where('table.users.uid = ?', $uid)
		    ->expression($field, "$field + $num")
			->affected();
	}
	
	/**
	 * 递减数值
	 *
	 * @access public
	 * @param int|string $uid 
	 * @param string     $field  
	 * @param int        $num 
	 * @return false|int 
	 */
	public function decr( $uid, $field, $num = 1 )
	{
		$num = max(1, (int) $num);
		
        /** 更新数值 $field >= 是防止UNSIGNED类型 数量已经是零 报错 */
		return $this->db->update('table.users')
		    ->where("table.users.uid = ? AND $field >= ?", $uid, $num)
		    ->expression($field, "$field - $num")
			->affected();
	}
}
